package com.hcms.system.controller;

import com.hcms.common.data.Tags;
import com.hcms.common.utils.Result;
import com.hcms.common.utils.StringUtil;
import com.hcms.system.domain.RoleDo;
import com.hcms.system.domain.RoleMenuDo;
import com.hcms.system.service.RoleMenuService;
import com.hcms.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/system/role")
@Controller
public class RoleController {
    String prefix = "system/role";

    @Autowired
    RoleService roleService;

    @Autowired
    RoleMenuService roleMenuService;

    @GetMapping()
    public String role() {
        return prefix + "/role";
    }

    @PostMapping("/list")
    @ResponseBody
    public Result list() {
        List<RoleDo> tree = roleService.tree();

        HashMap<String, Object> result = new HashMap<>();
        result.put("count", 1000);
        result.put("data", tree);

        return Result.ok(result);
    }

    @GetMapping("/add/")
    public String add(@RequestParam(name = "parentId", required = false) Integer parentId, Model model) {
        int parentIdInfo = 1;
        if (parentId != null && parentId > 0) {
            parentIdInfo = parentId;
        }
        model.addAttribute("parentId", parentIdInfo);
        model.addAttribute("markStatusData", new Tags().markStatusData());

        return prefix + "/add";
    }

    @PostMapping("/save")
    @ResponseBody
    public Result save(RoleDo role) {
        role.setCreateUser("admin");
        role.setUpdateUser("admin");

        RoleDo parentInfo = roleService.get(role.getParentId());
        String parentPath = parentInfo.getParentPath();
        parentPath = new StringUtil().stringDefault(parentPath, "");
        parentPath = parentPath + "," + role.getParentId() + ",";
        parentPath = new StringUtil().removeRepeatSymbol(parentPath, ",");
        role.setParentPath(parentPath);

        int count = roleService.save(role);
        if (count > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @GetMapping("/edit/{id}/")
    public String edit(@PathVariable("id") int id, Model model) {
        RoleDo roleDo = roleService.get(id);
        model.addAttribute("role", roleDo);
        model.addAttribute("markStatusData", new Tags().markStatusData());

        return prefix + "/edit";
    }

    @PostMapping("/update")
    @ResponseBody
    public Result update(RoleDo role) {
        role.setUpdateUser("admin");

        RoleDo parentInfo = roleService.get(role.getParentId());
        String parentPath = parentInfo.getParentPath();
        parentPath = new StringUtil().stringDefault(parentPath, "");
        parentPath = parentPath + "," + role.getParentId() + ",";
        parentPath = new StringUtil().removeRepeatSymbol(parentPath, ",");
        role.setParentPath(parentPath);

        int count = roleService.update(role);
        if (count > 0) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @PostMapping("/tree")
    @ResponseBody
    public List<RoleDo> tree() {
        List<RoleDo> tree = roleService.tree();
        return tree;
    }

    // 权限配置 页面
    @GetMapping("/setmenu/")
    public String setMenu(int id, Model model) {
        RoleDo roleDo = roleService.get(id);
        model.addAttribute("role", roleDo);

        List<RoleMenuDo> roleMenuList = roleMenuService.listByRoleId(id);
        String roleMenuIds = "";
        if (roleMenuList != null && !roleMenuList.isEmpty()) {
            roleMenuIds = roleMenuList.stream()
                    .filter(t -> t.getMarkStatus() == 0)
                    .map(t -> Integer.toString(t.getMenuId()))
                    .collect(Collectors.joining(","));
        }
        model.addAttribute("roleMenuIds", roleMenuIds);

        return prefix + "/setMenu";
    }

    // 保存 权限配置
    @PostMapping("/savemenu/")
    @ResponseBody
    public Result saveMenu(int roleId, String menuIds) {
        String[] menuIdStr = menuIds.split(",");

        // 新增
        for (String menuIdItem : menuIdStr) {
            int menuId = Integer.parseInt(menuIdItem);

            boolean isExist = roleMenuService.isExistMenu(roleId, menuId);
            if (!isExist) {
                RoleMenuDo roleMenuDo = new RoleMenuDo();
                roleMenuDo.setCreateUser("admin");
                roleMenuDo.setUpdateUser("admin");
                roleMenuDo.setMarkStatus(0);
                roleMenuDo.setRoleId(roleId);
                roleMenuDo.setMenuId(menuId);
                roleMenuService.save(roleMenuDo);
            } else {
                RoleMenuDo normalMenu = new RoleMenuDo();
                normalMenu.setRoleId(roleId);
                normalMenu.setMenuId(menuId);
                normalMenu.setMarkStatus(0);
                normalMenu.setUpdateUser("admin");
                roleMenuService.update(normalMenu);
            }
        }

        // 删除
        List<RoleMenuDo> allMenu = roleMenuService.listByRoleId(roleId);
        if (allMenu != null && !allMenu.isEmpty()) {
            for (RoleMenuDo roleMenuItem : allMenu) {

                boolean isDelete = true;
                for (String menuIdItem : menuIdStr) {
                    int menuId = Integer.parseInt(menuIdItem);
                    if (roleMenuItem.getMenuId() == menuId) {
                        isDelete = false;
                        break;
                    }
                }

                if (isDelete) {
                    RoleMenuDo deleteMenu = new RoleMenuDo();
                    deleteMenu.setRoleId(roleId);
                    deleteMenu.setMenuId(roleMenuItem.getMenuId());
                    deleteMenu.setMarkStatus(-1);
                    deleteMenu.setUpdateUser("admin");
                    roleMenuService.update(deleteMenu);
                }
            }
        }

        return Result.ok();
    }
}
